const app = getApp();

import services from '../../services/clockin';
import ddUtil from '../../utils/ddUtil';
import timeHelper from '../../utils/timeHelper';
import common from '../../utils/common';

Page({
  data: {
    userInfo: null, // 用户信息
    employInfo: null, // 用户信息
    isManage: false,
    locAuthStatus: 0, // 0 未获取 1已授权 2未授权
    locationInfo: null, // 位置信息
    allowStations: [], // 允许打卡工地
    stationOptions: [],
    selectStation: '',
    constructionSite: {}, // 当前所处工地
    lastConstructionSite: null, // 上次打卡的工地
    isOuting: false, // 外勤打卡

    employeeWorkStartTime: null, // 上班打卡时间
    employeeWorkEndTime: null, // 下班打卡时间

    companyName: '上海尚格建筑装饰',
    isReady: false,
    shiftType: '', // 班次选择
    showShiftChoose: '', // 显示班次选择

    serverTime: '', // 服务器时间
    currentTime: 0, // 当前时间
    showTime: '', // 显示时间
    pageTimer: null, // timer
    isLoading: false,
    showSuccessToast: false,
    approveNum: '',
    remainDialog: {
      visible: false,
      info: {}
    }, // 当前所处工地

  },
  async onLoad() {
    this.updateVersion();
    dd.showLoading({
      content: '加载中...',
      delay: 1000
    });
    await this.initData();
    this.setData({
      isReady: true
    });
    dd.hideLoading();
  },
  async onShow() {
    if (this.data.isReady) {
      await this.initData();
    }
  },
  onUnload() {
    this.clearPageTimer();
  },
  async initData(isFirst = true) {
    this.initTimeInfo();
    const promiseList = [this.queryLocationInfo()];
    this.initUserInfo();
    if (!this.data.userInfo) {
      promiseList.push(this.queryUserInfo());
    }
    await this.queryGetUserEmployeeInfo();
    if (this.data.isManage) {
      await this.queryGetApprovePreview();
    }
    await Promise.all(promiseList);
    if (this.data.userInfo && this.data.locationInfo) {
      await this.queryPostNearStation();
      this.clearPageTimer();
      this.startPageTimer();
    }
    if (this.data.isOuting || [0, 1].includes(this.data.shiftType)) {
      await this.queryGetClockStatus();
    }
    await this.queryGetClockRemind();
  },
  initTimeInfo() {
    const serverTime = new Date().getTime();
    const currentTime = timeHelper.getSeconds(serverTime);
    app.globalData.serverTime = serverTime;
    const showTime = timeHelper.formatTime(currentTime);
    this.setData({
      serverTime,
      currentTime,
      showTime
    });
  },
  initUserInfo() {
    let res = dd.getStorageSync({
      key: 'newUserInfo'
    });
    if (res && res.data) {
      const userInfo = res.data;
      this.setData({
        userInfo
      });
      app.globalData.userInfo = userInfo;
    }
  },
  // 获取用户信息
  async queryUserInfo() {
    try {
      const authCode = await ddUtil.ddGetAuthCode(app.globalData.corpId);
      console.log('授权码', authCode);
      const userRes = await services.getUserInfo({
        authCode
      });
      if (userRes && userRes.data && userRes.data.code == 0 && userRes.data.data) {
        const userInfo = userRes.data.data;
        app.globalData.userInfo = userInfo;
        dd.setStorage({
          key: 'newUserInfo',
          data: {
            ...userInfo
          }
        });
        this.setData({
          userInfo
        });
        console.log('newUserInfo', userInfo);
        const {
          device_id,
          name,
          unionid,
          userid
        } = userInfo;
        const params = {
          deviceid: device_id || '',
          name: name || '',
          unionid: unionid || '',
          userid: userid || ''
        };
        const regRes = await services.postUserInfo(params);
        console.log('注册 userInfo', regRes);
        return;
      } else {
        common.showErrorToast(userRes);
      }
    } catch (error) {
      console.log(error);
      common.showErrorToast(error);
    }
  },
  // 获取位置信息
  async queryLocationInfo() {
    try {
      const res = await ddUtil.ddGetLocation();
      const {
        longitude,
        latitude,
        accuracy,
        province,
        city,
        address
      } = res || {};
      // const { accuracy, province, city, address } = res || {};
      // const longitude = '121.392';
      // const latitude = '31.2667';
      this.setData({
        locationInfo: {
          longitude: common.formatPosotion(longitude),
          latitude: common.formatPosotion(latitude),
          accuracy,
          province,
          city,
          address
        },
        locAuthStatus: 1
      });
      console.log('location:', this.data.locationInfo, this.data.locAuthStatus, res);
    } catch (error) {
      this.setData({
        locAuthStatus: 2
      });
      common.showErrorToast('无法获取位置信息，请打开定位服务');
      
    }
  },
  async queryGetUserEmployeeInfo() {
    try {
      const {
        unionid
      } = this.data.userInfo || {};

      const employRes = await services.getUserEmployeeInfo(unionid);
      if (employRes && employRes.data) {
        app.globalData.employInfo = employRes.data;
        this.setData({
          employInfo: employRes.data,
          isManage: employRes.data.is_manager === 1
        });
      }
      console.log('queryGetUserEmployeeInfo', employRes);
    } catch (error) {
      console.log('获取打卡状态失败', error);
      common.showErrorToast(error);
      this.setData({
        isOuting: false,
        constructionSite: {} // 当前所处工地
      });
    }
  },
  // 获取当前打卡站点信息
  async queryPostNearStation() {
    try {
      const {
        unionid
      } = this.data.userInfo || {};
      const {
        longitude,
        latitude
      } = this.data.locationInfo || {};
      const params = {
        longitude,
        latitude
      };
      const stationRes = await services.postNearStation(params, unionid);
      let constructionSite = {};
      let allowStations = [];
      if (stationRes && stationRes.data && stationRes.data.length) {
        allowStations = stationRes.data.filter((sitem) => sitem.allow_clock)
        const currentStation = allowStations[0] || {};
        constructionSite = currentStation.station || {};
      }
      const isOuting = !!(!constructionSite || !constructionSite.id);
      this.setData({
        isOuting,
        constructionSite: allowStations.length === 1 ? constructionSite : {},
        stationOptions: allowStations.map(item => {
          return {
            text: item.station.name,
            value: item.station.id,
            info: item
          }
        })
      });
      console.log('queryPostNearStation', isOuting, stationRes.data, this.data.constructionSite);
    } catch (error) {
      console.log('获取打卡状态失败', error);
      common.showErrorToast(error);
      this.setData({
        isOuting: false,
        constructionSite: {} // 当前所处工地
      });
    }
  },
  handleChangeStation(value, items, e) {
    if (value === undefined) {
      this.setData({
        selectStation: '',
        constructionSite: {},
      });
      return
    }
    const constructionSite = items.info.station || {};
    this.setData({
      selectStation: value,
      constructionSite,
    });
  },
  async queryGetClockStatus() {
    try {
      const {
        unionid
      } = this.data.userInfo || {};
      let res = {};
      if (this.data.isOuting) {
        const {
          longitude,
          latitude
        } = this.data.locationInfo || {};
        res = await services.getClockOutingStatus(unionid, longitude, latitude);
      } else {
        const {
          id
        } = this.data.constructionSite || {};
        const day = timeHelper.formatSearchDay(this.data.serverTime);
        const params = {
          day,
          shift_type: this.data.shiftType,
          station_id: id
        };
        res = await services.getClockStatus(params, unionid);
      }
      if (res && res.data) {
        this.setData({
          employeeWorkStartTime: res.data.employee_work_start_time || null,
          employeeWorkEndTime: res.data.employee_work_end_time || null
        });
      }
      console.log('queryGetClockStatus', res);
    } catch (error) {
      console.log('获取当前打卡状态失败', error);
      common.showErrorToast(error);
      this.setData({
        employeeWorkStartTime: null, // 上班打卡时间
        employeeWorkEndTime: null // 下班打卡时间
      });
    }
  },
  async queryGetClockRemind() {
    try {
      const {
        unionid
      } = this.data.userInfo || {};
      const res = await services.getClockRemind(unionid);
      console.log('queryGetClockRemind', res)
      if (res && res.data && res.data.popup) {
        const {
          station,
          on_duty,
          shift_type,
        } = res.data
        const stationDesc = station ? station.name : ''
        const shiftDesc = shift_type === 0 ? '白班' : '夜班'
        const dutyDesc = on_duty ? '下班' : '上班'
        const content = `您在 ${stationDesc||''}工地 ${shiftDesc||''} ${dutyDesc} 状态为缺卡`
        this.setData({
          remainDialog: {
            visible: true,
            info: {
              ...res.data,
              content
            }
          }
        })
      }
      console.log('queryGetClockRemind', res);
    } catch (error) {
      console.log('获取失败', error);
    }
  },
  handleCloseRemain() {
    this.setData({
      remainDialog: {
        visible: false,
        info: {}
      }
    })
  },
  handleConfirmRemain() {
    const {
      station,
      shift_type,
      on_duty
    } = this.data.remainDialog.info
    const stationId = station ? station.id : ''
    const clockType = on_duty ? 1 : 0
    const shiftType = shift_type || 0
    let url = '/page/reissue/reissue';
    url = url + `?stationId=${stationId||''}&mode=${stationId||!info?0:1}&clockType=${clockType||0}&shiftType=${shiftType||0}`;
    dd.navigateTo({
      url
    });
    this.handleCloseRemain()
  },
  // 打卡
  async handleClockIn(e) {
    if (this.data.isLoading) {
      return;
    }
    this.setData({
      isLoading: true
    });
    // 未授权
    if (this.data.locAuthStatus === 2) {
      await this.initData(false);
      this.setData({
        isLoading: false
      });
      return;
    }
    const {
      type
    } = e.currentTarget.dataset || {}; // 打卡类型 0: 上班打卡 1: 下班打卡
    if (type === 0 && !!this.data.employeeWorkStartTime) {
      this.setData({
        isLoading: false
      });
      return;
    }
    // 外勤打卡
    if (this.data.isOuting) {
      dd.navigateTo({
        url: `/page/outclock/outclock?clockType=${type}`
      });
      this.setData({
        isLoading: false
      });
      return;
    }
    // 打卡
    const {
      id
    } = this.data.constructionSite || {};
    const {
      unionid
    } = this.data.userInfo || {};
    const {
      longitude,
      latitude
    } = this.data.locationInfo || {};
    await this.queryClockPunch({
      station_id: id,
      unionid,
      latitude: latitude,
      longitude: longitude,
      shift_type: this.data.shiftType, // 班次：0白班 1夜班
      clock_type: type // 打卡类型 0: 上班打卡 1: 下班打卡
    });
    this.setData({
      isLoading: false
    });
  },
  // 请求打卡
  async queryClockPunch(params) {
    try {
      const res = await services.postClockPunch(params);
      // if (res && res.code === 200) {
      await this.queryGetClockStatus();
      dd.showToast({
        type: 'success',
        content: '打卡成功',
        duration: 2000
      });
      // } else {
      //   common.showErrorToast(res);
      // }
      // this.setData({
      //   employeeWorkStartTime: res.data.employee_work_start_time || null,
      //   employeeWorkEndTime: res.data.employee_work_end_time || null
      // });
    } catch (error) {
      console.log('打卡失败', error);
      common.showErrorToast(error);
    }
  },
  handleCloseToast() {
    this.setData({
      showSuccessToast: false
    });
  },
  // 开始计时
  startPageTimer() {
    const pageTimer = setInterval(() => {
      const currentTime = this.data.currentTime + 1;
      const showTime = timeHelper.formatTime(currentTime);
      this.setData({
        currentTime,
        showTime
      });
    }, 1000);
    this.setData({
      pageTimer
    });
  },
  // 清除计时
  clearPageTimer() {
    if (this.data.pageTimer) {
      clearInterval(this.data.pageTimer);
      this.setData({
        pageTimer: null
      });
    }
  },
  handleShowShiftChoose() {
    this.setData({
      showShiftChoose: true
    });
  },
  handleClickShift(e) {
    if (!this.data.constructionSite || !this.data.constructionSite.id) {
      dd.showToast({
        // type: '',
        content: '请选择打卡工地',
        duration: 2000
      });
      return;
    }
    if (this.data.showShiftChoose) {
      this.setData({
        showShiftChoose: false
      });
    }
    const {
      type
    } = e.currentTarget.dataset || {};
    if (String(type) === String(this.data.shiftType)) {
      return;
    }
    this.setData({
      shiftType: Number(type)
    });
    this.queryGetClockStatus();
  },
  updateVersion() {
    if (app.globalData.updateManager) {
      console.log('至下次冷启动前不再检查更新-clock');
      return;
    }
    let updateManager = dd.getUpdateManager();
    updateManager.onCheckForUpdate((res) => {
      const {
        hasUpdate
      } = res || {};
      console.log('是否有更新', res);
      if (hasUpdate) {
        updateManager.onUpdateReady((ret) => {
          console.log('更新版本号:', ret.version);
          dd.confirm({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            confirmButtonText: '是',
            cancelButtonText: '否',
            success: (res) => {
              if (res && res.confirm) {
                updateManager.applyUpdate();
              }
            }
          });
        });
      }
      app.globalData.updateManager = true;
    });
    updateManager.onUpdateFailed(() => {
      // 新版本下载失败
      dd.alert({
        title: '新版本下载失败！请稍后重试！',
        buttonText: '我知道了',
        success: () => {}
      });
    });
  },
  handleJumpApproval() {
    dd.navigateTo({
      url: `/page/approve/approve`
    });
  },
  async queryGetApprovePreview() {
    try {
      const {
        unionid
      } = this.data.userInfo || {};

      const res = await services.getApprovePreview(unionid);
      if (res && res.data) {
        this.setData({
          approveNum: res.data.approve_count || ''
        });
      }
    } catch (error) {
      console.log(error);
    }
  }
});